import { type Ref } from "vue";
class AudioCls {
  innerAudioContext?: UniApp.InnerAudioContext;
  active: Ref<number>;
  constructor() {
    this.active = ref(0);
    this.init();
  }
  setSrc() {}
  init(): UniApp.InnerAudioContext {
    if (!this.innerAudioContext) {
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.onPlay(() => this.onplay());
      this.innerAudioContext.onEnded(() => this.onEnded());

      this.innerAudioContext.onError((res) => {
        console.log(res.errMsg);
        console.log(res.errCode);
      });
    }
    return this.innerAudioContext;
  }
  play(src: string, id: number) {
    let innerAudioContext = this.innerAudioContext;
    if (!innerAudioContext) {
      innerAudioContext = this.init();
    }
    if (this.active.value !== id) {
      this.active.value = id;

      innerAudioContext.stop();
      innerAudioContext.src = src;
      innerAudioContext.play();
    } else {
      innerAudioContext.stop();
      this.active.value = 0;
    }
  }
  stop() {
    this.innerAudioContext?.stop();
  }
  onplay() {}
  onEnded() {
    console.log('结束播放');
    
    this.active.value=0
  }
  onError() {}
}
const Audios = new AudioCls();
export default Audios;
